package com.hengpeng.itfin.service.activity.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.itfin.common.MessageUtil;
import com.hengpeng.itfin.service.activity.RewardAddRateService;
import com.hengpeng.itfin.service.impl.BaseServiceImpl;
import com.hengpeng.itfinbase.en.ActivityStatus;
import com.hengpeng.itfinbase.en.RewardAddRateStatus;
import com.hengpeng.itfinbase.en.RewardLevel;
import com.hengpeng.itfinbase.en.UserLevel;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.activity.VipAddRateRequest;
import com.hengpeng.itfinbase.persist.Activity;
import com.hengpeng.itfinbase.persist.ReceivePlan;
import com.hengpeng.itfinbase.persist.Reward;
import com.hengpeng.itfinbase.persist.RewardAddRate;
import com.hengpeng.itfinbase.persist.SystemLog.LogType;
import com.hengpeng.itfinbase.persist.UserInfo;

@Transactional
@Service
@Lazy
public class RewardAddRateServiceImpl extends BaseServiceImpl implements RewardAddRateService {

    @Override
    public ResponseMessage vipAddRate(VipAddRateRequest request) {
        if (request.getUserId() == null || request.getActivityType() == null || request.getBorrowInfoId() == null
                || request.getInvestInfoId() == null || request.getInvestMoney() == null) {
            serviceFactory.getSystemLogService().addLog("","", LogType.ACTIVITYSET_EXCEPTION, 
                    "活动请求[" + request.getTransType() + "],参数错误");
            logger.error("活动请求[" + request.getTransType() + "],参数错误");
            return MessageUtil.GetSuccessMessage();
        }
        logger.info("开始进入活动[transtype=" + request.getTransType() + "][activityType=" + request.getActivityType()
                + "]业务操作");
        Activity activity = daoFactory.getActivityDao().getActivityByType(request.getActivityType());
        if (activity.getStatus() != ActivityStatus.ACTIVE) {
            serviceFactory.getSystemLogService().addLog("",activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION, 
                    "活动[" + activity.getActivityType() + "]已暂停或还未开始");
            logger.error("活动[" + activity.getActivityType() + "]已暂停或还未开始");
            return MessageUtil.GetSuccessMessage();
        }
        UserInfo userInfo = serviceFactory.getDaoFactory().getUserInfoDao().get(request.getUserId());
        if (userInfo.getUserLevel() == UserLevel.LEVEL_ZERO) {
            logger.error("用户[id=" + userInfo.getId() + "]等级为[LEVEL_ZERO]不参加加息活动");
            return MessageUtil.GetSuccessMessage();
        }
        Set<Reward> rewards = activity.getRewards();
        if (rewards == null || rewards.size() < 1) {
            serviceFactory.getSystemLogService().addLog("",activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION, 
                    "活动[id=" + activity.getId() + "]没有配置奖品");
            logger.error("活动[id=" + activity.getId() + "]没有配置奖品");
            return MessageUtil.GetSuccessMessage();
        }
        Reward rewardLevelOne = null, rewardLevelTwo = null, rewardLevelThree = null, rewardLevelFour = null, rewardLevelFive = null;
        Iterator<Reward> itereward = rewards.iterator();
        while (itereward.hasNext()) {
            Reward r = itereward.next();
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELONE) {
                rewardLevelOne = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTWO) {
                rewardLevelTwo = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELTHREE) {
                rewardLevelThree = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELFOUR) {
                rewardLevelFour = r;
            }
            if (r != null && r.getRewardLevel() == RewardLevel.LEVELFIVE) {
                rewardLevelFive = r;
            }
        }
        if (rewardLevelOne == null || rewardLevelTwo == null || rewardLevelThree == null || rewardLevelFour == null
                || rewardLevelFive == null) {
            serviceFactory.getSystemLogService().addLog("",activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION,
                    "活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
            logger.error("活动[activityid=" + activity.getId() + "]奖品信息配置错误,请检查");
            return MessageUtil.GetSuccessMessage();
        }
        Reward useReward = null;
        if (userInfo.getUserLevel() == UserLevel.LEVEL_ONE) {
            useReward = rewardLevelOne;
        } else if (userInfo.getUserLevel() == UserLevel.LEVEL_TWO) {
            useReward = rewardLevelTwo;
        } else if (userInfo.getUserLevel() == UserLevel.LEVEL_THREE) {
            useReward = rewardLevelThree;
        } else if (userInfo.getUserLevel() == UserLevel.LEVEL_FOUR) {
            useReward = rewardLevelFour;
        } else if (userInfo.getUserLevel() == UserLevel.LEVEL_FIVE) {
            useReward = rewardLevelFive;
        }
        if (useReward == null) {
            serviceFactory.getSystemLogService().addLog("",activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION,
                    "活动[activityid=" + activity.getId() + "],用户[id=" + userInfo.getId() + "]奖品信息不对应");
            logger.error("活动[activityid=" + activity.getId() + "],用户[id=" + userInfo.getId() + "]奖品信息不对应");
            return MessageUtil.GetSuccessMessage();
        }
        ReceivePlan lastReceivePlan = serviceFactory.getDaoFactory().getReceivePlanDao()
                .getLatestReceivePlans(request.getInvestInfoId());
        if (lastReceivePlan == null) {
            serviceFactory.getSystemLogService().addLog("",activity.getId().toString(), LogType.ACTIVITYSET_EXCEPTION, 
                    "投标[id=" + request.getInvestInfoId() + "]找不到对应的收款计划");
            logger.error("投标[id=" + request.getInvestInfoId() + "]找不到对应的收款计划");
            return MessageUtil.GetSuccessMessage();
        }
        RewardAddRate rewardAddRate = new RewardAddRate();
        rewardAddRate.setActiveid(activity.getId());
        rewardAddRate.setAddRate(new BigDecimal(Double.parseDouble(useReward.getRewardVal())));
        rewardAddRate.setBorrowInfoId(request.getBorrowInfoId());
        rewardAddRate.setCreateTime(new Date());
        rewardAddRate.setInvestInfoId(request.getInvestInfoId());
        rewardAddRate.setMoney(new BigDecimal(Double.parseDouble(useReward.getRewardVal()) * request.getInvestMoney()));
        rewardAddRate.setPayTime(lastReceivePlan.getArrivalTime());
        rewardAddRate.setStatus(RewardAddRateStatus.UNPAY);
        rewardAddRate.setUpdateTime(new Date());
        rewardAddRate.setUserId(request.getUserId());
        rewardAddRate = daoFactory.getRewardAddRateDao().save(rewardAddRate);
        if (rewardAddRate.getId() == null) {
            serviceFactory.getSystemLogService().addLog("",
                    activity.getId().toString(),
                    LogType.ACTIVITYSET_EXCEPTION,
                    "用户[id=" + request.getUserId() + "],投标[id=" + request.getInvestInfoId() + "],标的[id="
                            + request.getBorrowInfoId() + "]加息失败.");
            logger.error("用户[id=" + request.getUserId() + "],投标[id=" + request.getInvestInfoId() + "],标的[id="
                    + request.getBorrowInfoId() + "]加息失败.");
        }
        logger.info("活动[transtype=" + request.getTransType() + "]业务操作结束");
        return MessageUtil.GetSuccessMessage();
    }

}
